<?php
declare (strict_types = 1);
// +----------------------------------------------------------------------
// | 管理员
// +----------------------------------------------------------------------

namespace app\admin\controller;

use app\common\model\Role;
use app\common\model\User;
use app\Request;
use think\facade\View;

class AdminController extends AdminBaseController
{
    /**
     * @OA\Get(path="/admin",tags={"管理员"},summary="列表",
     *   @OA\Parameter(name="authorization", in="header", description="Bearer token", @OA\Schema(type="string")),
     *   @OA\Parameter(name="page", in="query", description="页码", @OA\Schema(type="int", default="1")),
     *   @OA\Parameter(name="limit", in="query", description="行数", @OA\Schema(type="int", default="10")),
     *   @OA\Response(response="200", description="successful operation")
     * )
     */
    public function index()
    {
        if ($this->request->isAjax()) {
            $request = $this->request->param();
            $where[] = ['user_type', '=', 1];
            if (!empty($request['id'])) {
                $where[] = ['id', '=', $request['id']];
            }
            if (!empty($request['username'])) {
                $where[] = ['username', '=', $request['username']];
            }
            if (!empty($request['email'])) {
                $where[] = ['email', '=', $request['email']];
            }
            $list = User::where($where)->order('id desc')->paginate(10);
            return $this->result($list->items(), '', ['count' => $list->total()]);
        }
        return View::fetch('user/admin/index');
    }

    public function create()
    {
        View::assign('role', Role::select());
        return View::fetch('user/admin/create');
    }

    /**
     * 保存新建的资源
     */
    public function save()
    {
        $result = User::assignAdmin($this->request->param());
        if ($result) {
            return $this->success('Success');
        }
        return $this->error('Error');
    }


    /**
     * 显示编辑资源表单页.
     *
     * @param  int  $id
     * @return string
     */
    public function edit($id)
    {
        $user = User::find($id);
        $roles = $user->roles;
        View::assign([
            'data' => $user,
            'role' => Role::select(),
            'ids'  => array_column( $roles->toArray(), 'id')
        ]);
        return View::fetch('user/admin/edit');
    }

    public function update(Request $request)
    {
        $result = User::syncAdmin($request->param());
        if ($result) {
            return $this->success('Success');
        }
        return $this->error('Error');
    }

    public function delete($id)
    {
        if ($id == 1) {
            return $this->error('Error');
        }
        $result = User::removeAdmin($id);
        if ($result) {
            return $this->success('Success');
        }
        return $this->error('Error');
    }
}
